package com.zhou.app.favourite.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhou.app.favourite.entity.FavIcon;
import com.zhou.app.favourite.mapper.FavIconMapper;
import com.zhou.app.favourite.service.service.IFavIconService;
import com.zhou.common.lib.model.ImageVo;
import com.zhou.common.lib.util.HttpUtil;
import com.zhou.common.lib.util.ShortcutIconUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 * 图标 服务实现类
 * </p>
 *
 * @author zxf
 * @since 2023-04-15
 */
@Service
public class FavIconServiceImpl extends ServiceImpl<FavIconMapper, FavIcon> implements IFavIconService {

    @Async
    @Override
    public void addIcon(String path) {
        String host = HttpUtil.getHost(path);
        LambdaQueryWrapper<FavIcon> queryWrapper = Wrappers.<FavIcon>lambdaQuery().eq(FavIcon::getHost, host);
        Integer integer = baseMapper.selectCount(queryWrapper);
        if (integer == 0) {
            ImageVo icon = ShortcutIconUtils.getIcon(path);
            FavIcon favIcon = new FavIcon();
            favIcon.setHost(host);
            favIcon.setIcon(icon.getContent());
            favIcon.setOriginPath(icon.getPath());
            baseMapper.insert(favIcon);
        }
    }

    @Override
    public void uploadImage(MultipartFile file, String originPath) throws IOException {
        InputStream inputStream = file.getInputStream();
        byte[] bytes = IOUtils.toByteArray(inputStream);
        FavIcon favIcon = new FavIcon();
        favIcon.setOriginPath(originPath);
        String host = HttpUtil.getHost(originPath);
        favIcon.setHost(host);
        favIcon.setIcon(bytes);

        LambdaQueryWrapper<FavIcon> eq = Wrappers.<FavIcon>lambdaQuery().eq(FavIcon::getHost, host);
        if (baseMapper.selectCount(eq) > 0) {
            LambdaUpdateWrapper<FavIcon> updateWrapper
                    = Wrappers.<FavIcon>lambdaUpdate().eq(FavIcon::getHost, host);
            baseMapper.update(favIcon, updateWrapper);
        } else {
            baseMapper.insert(favIcon);
        }
    }
}
